/**
 * @class Bible.ReadContainer
 * @extends Ext.Container
 */
Bible.ReadContainer = Ext.extend(Ext.Container, {
    layout: 'card',
    border: false,
    deferredRender: true,
    hideMode:'offsets',

    initComponent: function(){
        var me = this;
        me.firstGrid = new Bible.BibleGridPanel({
			id: 'base-grid',
            region: 'center',
            hashBook: 'b1'
        });
        me.secondGrid = new Bible.BibleGridPanel({
            hashBook: 'b2'
        });

        me.tabPanel = new Ext.TabPanel({
            hashBook: 'tabs',
            deferredRender: true,
            enableTabScroll:true,
            resizeTabs:true, // turn on tab resizing
            minTabWidth: 115,
            tabWidth:145,
            activeTab: Bible.defaults.layout == 'tabs' ? 0 : undefined,
            plugins: [
                new Ext.ux.TabCloseMenu(),
                new Bible.plugins.TabPanelAddButton({
                    maxLimit: 10,
                    addButton: new Ext.Button({
                        tooltip: 'Adaugă un Tab', // TODO i18n
                        iconCls: 'add-tab',
                        scope: me,
                        handler: function(){
                            console.debug('onBtnAddClick');
                            me.addBibleGridTab(true, true);
                        }
                    })
                })
            ],
            listeners: {
                tabchange: function(tabPanel, tab){
                    // fix bug when grid.bbar is not visible after tabchange
                    //tab.doLayout();
                    tab.getBottomToolbar().doLayout();
                }
            },
            items: [
                me.tab1 = new Bible.BibleGridPanel({
                    title: i18n.bible,
                    autoLoadChapter: Bible.defaults.layout != 'tabs',
                    //hashBook: 'b1',
                    border: false,
                    listeners: {
                        scope: me,
                        pagechange: me.tabPageChange
                    }
                })
            ]
        });

        var w = (Ext.getBody().getWidth()-10) / 2, // 5 from Search sidebar, 5 from splitter
            h = (Ext.getBody().getHeight()-48) / 2;  // 48 from tbar
        Ext.apply(me, {
            activeItem: Bible.defaults.layout != 'tabs' ? 0 : 1,
            items: [
                me.boxContainer = new Ext.Container({
                    hideMode:'offsets',
                    layout: 'border',
                    items: [
                        me.firstGrid,
                        me.bottomContainer = new Ext.Container({
                            id: 'bottom-preview',
                            layout:'fit',
                            region:'south',
                            height: h ? h : 250,
                            split: true,
                            border: true,
                            hidden: Bible.defaults.layout != 'vbox',
                            items: Bible.defaults.layout == 'vbox' ? me.secondGrid : []
                        }),
                        me.rightContainer = new Ext.Container({
                            id: 'right-preview',
                            layout:'fit',
                            region:'east',
                            width: w ? w : 500,
                            split: true,
                            border: true,
                            hidden: Bible.defaults.layout != 'hbox',
                            items: Bible.defaults.layout == 'hbox' ? me.secondGrid : []
                        })
                    ]
                }),
                me.tabPanel
            ]
        });

        /**
         * current view type
         * @type String
         * @property currentType
         */
        me.currentType = Bible.defaults.layout;

        Bible.ReadContainer.superclass.initComponent.call(me);

        me.readTabActions();
    },

    afterRender : function(){
        Bible.ReadContainer.superclass.afterRender.call(this);
        this.initEvents();
    },

    initEvents: function() {
        var me = this;

        me.tab1.on({
            scope: me,
            refclick: function(id, text){
                console.debug('refclick on tab1', id, text);
                var g = me.addBibleGridTab(false, false);
                if(g){
                    g.getVerseDetails(id, text);
                }
            }
        });

        me.firstGrid.on({
            scope: me,
            refclick: function(id, text){
                console.debug('refclick on firstGrid', id, text);
                //if(Bible.viewPort.panel.getTopToolbar().boxButton.pressed){
                if(me.currentType == 'box'){
                    Bible.viewPort.panel.getTopToolbar().hboxButton.toggle(true);
                }
                me.secondGrid.getVerseDetails(id, text);
            }
        });

        me.secondGrid.on({
            scope: me,
            refclick: function(id, text){
                console.debug('refclick on secondGrid', id, text);
                me.firstGrid.getVerseDetails(id, text);
            }
        });
    },

    addBibleGridTab: function(show, autoLoadChapter){
        var me = this;
        if(me.tabPanel.items.getCount() < 10){ //maxLimit
            var grid = new Bible.BibleGridPanel({
                //xtype: 'biblegridpanel',
                title: i18n.bible,
                closable:true,
                autoLoadChapter: autoLoadChapter,
                listeners: {
                    scope: me,
                    pagechange: me.tabPageChange
                }
            });
            //this.tabPanel.add(grid).show();
            me.tabPanel.add(grid);
            if(show){
                grid.show();
            }
            grid.on({
                scope: me,
				destroy: function(){
					me.setTabActions();
				},
                refclick: function(id, text){
                    console.debug('refclick on tab', id, text);
                    var g = this.addBibleGridTab(false, false);
                    if(g){
                        g.getVerseDetails(id, text);
                    }
                }
            });
            return grid;
        } else {
            console.warn('can not add more that 10 tabs');
            return false;
        }

    },

    // private
    tabPageChange: function(grid, params){
        var title = grid.booksStore.getById(params.book).get('name') + ' ' + params.chapter;
        if(title.length > 15){
            title = '<span qtip="'+title+'">'+title+'</span>';
        }
        grid.setTitle(title);
        this.setTabActions();
    },

    /**
     *
     */
    setTabActions: function(){
        var me = this,
            tabPanel = me.tabPanel,
            action = [],
            separator = '.';
        if(!me.pauseChangeUrl){
            tabPanel.items.each(function(g){
                action.push(g.booksCombo.getValue() + separator + g.chaptersCombo.getValue());
            });
            Bible.setActions(tabPanel.hashBook, action.join('-'));
        }
    },

    /**
     *
     */
    readTabActions: function(){
        var me = this,
            grid,
            chapter,
            action = Bible.getAction(me.tabPanel.hashBook);
        console.debug('readTabActions: ', action);
        if(action){
            action = action.split('-');
            me.pauseChangeUrl = true;
            Ext.each(action, function(params, index){
                chapter = params.split('.');
                console.debug('params, chapter, index: ', params, chapter, index);
                if(index){
                    grid = me.addBibleGridTab(false, false);
                    if(grid){
                        grid.setPage({
                            book: chapter[0],
                            chapter: chapter[1]
                        });
                    }
                } else {
                    console.warn('set first grid values (title and store is not changed)');
                    grid = me.tab1;
                    grid.setPage({
                        book: chapter[0],
                        chapter: chapter[1]
                    });
                }
            });
            me.pauseChangeUrl = false;
        }
    },

    /**
     * @param {Ext.Button} button
     */
    moveSecondView : function(button, pressed){
        var me = this,
            bottom = me.bottomContainer,
            right = me.rightContainer,
            second = me.secondGrid,
            tabPanel = me.tabPanel,
            layout = this.getLayout(),
            action,
            separator = '.';
        if(pressed){
            me.currentType = button.type;
            switch(button.type){
                case 'vbox':
                    layout.setActiveItem(0);
                    right.hide();
                    bottom.add(me.secondGrid);
                    bottom.show();
                    bottom.ownerCt.doLayout();
                    action = second.booksCombo.getValue() + separator + second.chaptersCombo.getValue();
                    Bible.setActions(second.hashBook, action);
                    Bible.removeAction(tabPanel.hashBook);
                    break;
                case 'hbox':
                    layout.setActiveItem(0);
                    bottom.hide();
                    right.add(me.secondGrid);
                    right.show();
                    right.ownerCt.doLayout();
                    action = second.booksCombo.getValue() + separator + second.chaptersCombo.getValue();
                    Bible.setActions(second.hashBook, action);
                    Bible.removeAction(tabPanel.hashBook);
                    break;
                case 'box':
                    layout.setActiveItem(0);
                    if(second.ownerCt){
                        second.ownerCt.hide();
                        second.ownerCt.ownerCt.doLayout();
                    }
                    Bible.removeAction(second.hashBook);
                    Bible.removeAction(tabPanel.hashBook);
                    break;
                case 'tabs':
                    me.getLayout().setActiveItem(1);
                    if(!tabPanel.getActiveTab()){
                        tabPanel.setActiveTab(0);
                    }
                    me.setTabActions();
                    Bible.removeAction(me.firstGrid.hashBook);
                    Bible.removeAction(second.hashBook);
                    break;
            }
//            Bible.setActions('layout', button.type);
            Bible.setActions('l', button.type);
        }
    },
	
	setBibleGridPage: function(record, searchValue, bibleGrid){
		console.debug('setBibleGridPage', record, searchValue);
		bibleGrid = bibleGrid || this.firstGrid;
		if(this.currentType == 'tabs'){
			console.debug('activeReader');
			bibleGrid = this.tabPanel.getActiveTab();
		}
		if(searchValue){
			bibleGrid.searchField.setValue(searchValue);
		}
		var params = {
			book: record.get('bnumber'),
			chapter: record.get('cnumber')
		};
		if(!bibleGrid.isEqual(params)){
			bibleGrid.setPage(params, record.get('vnumber'));
		} else {
			console.debug('store unchanged: selectRow & focusRow');
			bibleGrid.selectVerse(record.get('vnumber'));
		}
	}
});

Ext.reg('readcontainer', Bible.ReadContainer);
